package ex02.pyrmont;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

import ex01.pyrmont.HttpServer;
import ex01.pyrmont.Request;
import ex01.pyrmont.Response;

public class ServletProcessor {

	public void process(Request request, Response response) {
		
		String uri = request.getUri();
		String servletName = uri.substring(uri.lastIndexOf("/") + 1);
		System.out.println("servletName : " + servletName);
		URLClassLoader   loader = null;
		URL[] urls = new URL[1];
		URLStreamHandler streamHandler = null;
		File classPath = new File(HttpServer.WEB_ROOT);
		try {
			String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
			System.out.println("repository : " + repository);
			urls[0] = new URL(null, repository, streamHandler);
			loader = new URLClassLoader(urls);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Class<?> myClass = null;
		try {
			myClass = loader.loadClass(HttpServer.SERVLET_PACKAGE + servletName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Servlet servlet = null;
		try {
			servlet = (Servlet) myClass.newInstance();
			servlet.service(request, response);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
